<template>
  <el-dialog
    v-if="visible"
    :close-on-click-modal="false"
    append-to-body
    :title="clickData.title"
    :visible.sync="visible"
    @close="cancel"
    :show="show"
    width="30%"
  >
    <el-form size="mini" @submit.native.prevent>
      <el-form-item v-if="!(clickData.type && clickData.type == '18')">
        <div style="width:80%; margin:auto">
          <el-input
            placeholder="请输入内容"
            v-model="filterText"
            class="input-with-select"
          >
            <el-button slot="append" icon="el-icon-search"></el-button>
          </el-input>
        </div>
      </el-form-item>
      <el-form-item>
        <div
          class="contentareawrap"
          style="margin-top: 10px; height: 300px; overflow-y: auto"
        >
          <el-tree
            class="filter-tree"
            node-key="id"
            :default-expanded-keys="defaultShowNodes"
            :expand-on-click-node="false"
            highlight-current
            :data="datalist"
            @node-expand="handleExpand"
            @node-collapse="handleCollapse"
            @node-click="handleNodeClick"
            :filter-node-method="filterNode"
            :props="clickData.defaultProps || params.defaultProps"
            ref="contenttree"
          >
          </el-tree>
        </div>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="cancel">取 消</el-button>
      <el-button type="primary" @click="addtag">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { createNamespacedHelpers } from 'vuex'
const { mapState, mapMutations } = createNamespacedHelpers('charts')
export default {
  name: 'areaDialog',
  inheritAttrs: false,
  props: {
    show: {
      type: Boolean,
      default: false
    },
    clickData: {
      type: Object,
      default: () => {}
    },
    params: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      visible: this.show,
      filterText: '',
      datalist: [],
      isshow: false,
      checkedId: [],
      checkedNode: [],
      areaShow: false,
      siteShow: false,
      oldDatalist: [
        {
          lable: '全部数据',
          id: '-9999',
          children: null,
          leaf: false,
          newlable: '全部数据'
        },
        {
          lable: '无问题数据',
          id: '99',
          children: null,
          leaf: false,
          newlable: '无问题数据'
        },
        {
          lable: '存在的问题',
          id: '98',
          leaf: false,
          newlable: '存在的问题',
          children: [
            {
              lable: '标题错误',
              id: '1',
              leaf: true,
              newlable: '标题错误'
            },
            {
              lable: '来源为空',
              newlable: '来源为空',
              id: '2',
              leaf: true
            },
            {
              lable: '正文为空',
              newlable: '正文为空',
              id: '3',
              leaf: true
            },
            {
              lable: '有其他链接',
              newlable: '有其他链接',
              id: '4',
              leaf: true
            },
            {
              lable: '时间错误',
              newlable: '时间错误',
              id: '5',
              leaf: true
            },
            {
              lable: '版权错误',
              newlable: '版权错误',
              id: '6',
              leaf: true
            },
            {
              lable: '疑似垃圾',
              newlable: '疑似垃圾',
              id: '7',
              leaf: true
            },
            {
              lable: '敏感非法文章（需要产品属性）',
              newlable: '敏感非法文章（需要产品属性）',
              id: '8',
              leaf: true
            }
          ]
        }
      ],
      currIndex: '',
      defaultShowNodes: [], // 这里存放要默认展开的节点 id
      mutiple: 0 // 0--单选 1--首次置为多选 2--第二次以后置为多选
    }
  },
  methods: {
    // 存取展开节点
    saveExpandNode(data) {
      let flag = false
      this.defaultShowNodes.some(item => {
        if (item === data.id) {
          // 判断当前节点是否存在， 存在不做处理
          flag = true
          return true
        }
      })
      if (!flag) {
        // 不存在则存到数组里
        this.defaultShowNodes.push(data.id)
      }
    },
    // 节点展开时的事件
    handleExpand(data) {
      let type = this.clickData.type || this.params.type
      switch (type) {
        case '18':
          this.saveExpandNode(data)
          break
      }
    },
    // 节点折叠时的事件
    handleCollapse(data) {
      let _this = this
      this.defaultShowNodes.some((item, i) => {
        if (item === data.id) {
          // 删除关闭节点
          _this.defaultShowNodes.slice(i, 1)
        }
      })
    },
    // 回显错误类型选中的值
    showSelectData(arr) {
      let _this = this
      arr.forEach(item => {
        let flag = _this.checkedId.find(item1 => item1 === item.id)
        item.lable = flag ? item.newlable + ' ✔' : item.lable
        if (item.children) {
          _this.showSelectData(item.children)
        }
      })
    },
    handleNodeClick(data, node, own) {
      let type = this.clickData.type || this.params.type
      switch (type) {
        case '4':
        case '13':
          this.setClickParentNode(data, node, own)
          break
        case '20':
          this.setClickChildrenNode(data, node, own)
          break
        case '22':
          switch (this.clickData.id) {
            case '0':
              this.setClickParentNode(data, node, own)
              break
            case '1':
              this.setClickChildrenNode(data, node, own)
              break
          }
          break
        case '18':
          this.setSpecialTreeNode(data, node, own)
          break
      }
    },
    // 查找当前点击节点的索引值
    findNode(arr, id) {
      let _this = this
      for (let index in arr) {
        let flag = arr[index].id === id
        if (flag) {
          this.currIndex =
            this.currIndex !== '' ? this.currIndex + ':' + index : index
          break
        } else {
          if (arr[index].children) {
            this.currIndex =
              this.currIndex !== '' ? this.currIndex + ':' + index : index
            _this.findNode(arr[index].children, id)
          }
        }
      }
    },
    // 父节点单选，子节点多选，子节点只有在选择了父节点后才能点击
    setSpecialTreeNode(data, node, own) {
      let _this = this
      this.currIndex = ''
      this.mutiple = data.leaf ? (this.mutiple === 0 ? 1 : 2) : 0
      let index1 = this.checkedId.findIndex(item => item == data.id)
      this.findNode(this.datalist, data.id)
      let splitArr = this.currIndex.split(':')
      if (index1 === -1) {
        switch (this.mutiple) {
          case 0:
          case 1:
            this.checkedId = []
            this.checkedNode = []
            this.datalist = JSON.parse(JSON.stringify(this.oldDatalist))
            this.defaultShowNodes.forEach(item => {
              item = Number(item)
              _this.$refs.contenttree.store.nodesMap[item].expanded = true
            })
            this.checkedId[0] = data.id
            this.checkedNode[0] = data.newlable
            splitArr[1]
              ? (this.datalist[splitArr[0]].children[splitArr[1]].lable =
                  data.newlable + ' ✔')
              : (this.datalist[splitArr[0]].lable = data.newlable + ' ✔')
            break
          case 2:
            this.checkedId.push(data.id)
            this.checkedNode.push(data.newlable)
            splitArr[1]
              ? (this.datalist[splitArr[0]].children[splitArr[1]].lable =
                  data.newlable + ' ✔')
              : (this.datalist[splitArr[0]].lable = data.newlable + ' ✔')
            break
        }
      } else {
        this.checkedId.splice(index1, 1)
        this.checkedNode.splice(index1, 1)
        splitArr[1]
          ? (this.datalist[splitArr[0]].children[splitArr[1]].lable =
              data.newlable)
          : (this.datalist[splitArr[0]].lable = data.newlable)
      }
    },
    setClickParentNode(data, node, own) {
      let index1 = this.checkedId.indexOf(data.id)
      if (index1 === -1) {
        this.checkedId.push(data.id)
        this.checkedNode.push(data.newlable)
        own.$children[0].$el.innerHTML = data.newlable + ' ✔'
      } else {
        this.checkedId.splice(index1, 1)
        this.checkedNode.splice(index1, 1)
        own.$children[0].$el.innerHTML = data.newlable
      }
    },
    setClickChildrenNode(data, node, own) {
      if (node.level !== 1) {
        this.setClickParentNode(data, node, own)
      }
    },
    addtag() {
      let type = this.clickData.type || this.params.type
      let param
      switch (type) {
        case '4':
          switch (this.clickData.id) {
            case '0':
              param = {
                territory1: this.checkedId,
                territory1Node: this.checkedNode
              }
              break
            case '1':
              param = {
                territory2: this.checkedId,
                territory2Node: this.checkedNode
              }
              break
            case '2':
              param = {
                territory3: this.checkedId,
                territory3Node: this.checkedNode
              }
              break
            case '3':
              param = {
                territory4: this.checkedId,
                territory4Node: this.checkedNode
              }
              break
          }
          break
        case '13':
          param = {
            infoSite: this.checkedId,
            infoSiteNode: this.checkedNode
          }
          break
        case '20':
          param = {
            sepcialSite: this.checkedId,
            sepcialSiteNode: this.checkedNode
          }
          break
        case '18':
          param = {
            err: this.checkedId,
            errLable: this.checkedNode
          }
          break
        case '22':
          switch (this.clickData.id) {
            case '0':
              param = {
                weoboUser: this.checkedId,
                weoboUserNode: this.checkedNode
              }
              break
            case '1':
              param = {
                sepcialWeioboUser: this.checkedId,
                sepcialWeioboUserNode: this.checkedNode
              }
              break
          }
          break
      }
      this.setNewFormData(param)
      this.$emit('update:show', false)
    },
    addSelectType(data) {
      for (let i in data) {
        if (this.checkedId.includes(data[i].id)) {
          if (!data[i].newlable) data[i].newlable = data[i].lable
          data[i].lable = data[i].newlable + ' ✔'
        } else {
          if (!data[i].newlable) data[i].newlable = data[i].lable
          data[i].lable = data[i].newlable
        }
        let children = data[i].children
        if (children && children.length > 0) {
          this.addSelectType(children)
        }
      }
      return data
    },
    // 获取地域属性树形结构的list
    getregionalList() {
      let that = this
      this.$axios.get('/getAreaTreeBeanList?fid=-1').then(res => {
        let result = res.data.result
        if (Object.prototype.toString.call(result) === '[object Array]') {
          result = that.addSelectType(result)
          that.datalist = result
        } else {
          that.datalist = []
        }
      })
    },
    // 获取采集位置列表树形结构
    getdowngatherlist() {
      let that = this
      this.$axios.get('/getPositionTreeBeanList').then(res => {
        let result = res.data.result
        if (Object.prototype.toString.call(result) === '[object Array]') {
          result = that.addSelectType(result)
          that.datalist = result
        } else {
          that.datalist = []
        }
      })
    },
    // 获取用户树形结构
    getWeiboUserlist() {
      let that = this
      this.$axios.get('/getWeiboUserType').then(res => {
        let result = res.data.result
        if (Object.prototype.toString.call(result) === '[object Array]') {
          result = that.addSelectType(result)
          that.datalist = result
        } else {
          that.datalist = []
        }
      })
    },
    // 获取特殊微博用户树形结构
    getSpecialWeibolist() {
      let that = this
      this.$axios.get('/getSpecialWeiboType').then(res => {
        let result = res.data.result
        if (Object.prototype.toString.call(result) === '[object Array]') {
          result = that.addSelectType(result)
          that.datalist = result
        } else {
          that.datalist = []
        }
      })
    },
    // 特殊站点加载树结点
    specialSiteloadNode(node, resolve) {
      let that = this
      this.$axios.get('/getSpecialMediaType').then(res => {
        let result = res.data.result
        if (Object.prototype.toString.call(result) === '[object Array]') {
          result = that.addSelectType(result)
          that.datalist = result
        } else {
          that.datalist = []
        }
      })
    },
    filterNode(value, data) {
      if (!value) return true
      return data.lable.indexOf(value) !== -1
    },
    cancel() {
      this.$emit('update:show', false)
    },
    ...mapMutations(['setNewFormData'])
  },
  computed: {
    ...mapState(['formData'])
  },
  watch: {
    filterText(val) {
      this.$refs.contenttree.filter(val)
    },
    async show(val) {
      let type = this.clickData.type || this.params.type
      this.filterText = ''
      this.visible = val
      if (val) {
        switch (type) {
          case '13':
            switch (this.clickData.id) {
              case '0':
                this.checkedNode = Array.from(this.formData.infoSiteNode)
                this.checkedId = Array.from(this.formData.infoSite)
                break
            }
            break
          case '4':
            switch (this.clickData.id) {
              case '0':
                this.checkedNode = Array.from(this.formData.territory1Node)
                this.checkedId = Array.from(this.formData.territory1)
                break
              case '1':
                this.checkedNode = Array.from(this.formData.territory2Node)
                this.checkedId = Array.from(this.formData.territory2)
                break
              case '2':
                this.checkedNode = Array.from(this.formData.territory3Node)
                this.checkedId = Array.from(this.formData.territory3)
                break
              case '3':
                this.checkedNode = Array.from(this.formData.territory4Node)
                this.checkedId = Array.from(this.formData.territory4)
                break
            }
            break
          case '20':
            this.checkedNode = Array.from(this.formData.sepcialSiteNode)
            this.checkedId = Array.from(this.formData.sepcialSite)
            break
          case '22':
            switch (this.clickData.id) {
              case '0':
                await this.getWeiboUserlist()
                this.checkedNode = Array.from(this.formData.weoboUserNode)
                this.checkedId = Array.from(this.formData.weoboUser)
                break
              case '1':
                await this.getSpecialWeibolist()
                this.checkedNode = Array.from(
                  this.formData.sepcialWeioboUserNode
                )
                this.checkedId = Array.from(this.formData.sepcialWeioboUser)
                break
            }
            break
          case '18':
            this.datalist = JSON.parse(JSON.stringify(this.oldDatalist))
            this.defaultShowNodes = []
            this.checkedId = Array.from(this.formData.err)
            this.checkedNode = Array.from(this.formData.errLable)
            this.showSelectData(this.datalist)
            break
        }
        let result = this.addSelectType(this.datalist)
        this.datalist = result
      }
    },
    resetFormData() {
      this.checkedId = []
      this.checkedNode = []
    }
  },
  mounted() {
    let type = this.clickData.type || this.params.type
    switch (type) {
      case '13':
        this.getdowngatherlist()
        break
      case '4':
        this.getregionalList()
        break
      case '20':
        this.specialSiteloadNode()
        break
      case '18':
        this.datalist = JSON.parse(JSON.stringify(this.oldDatalist))
        break
    }
  }
}
</script>

<style scoped></style>
